package com.ghostflying.groundstation;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Locale;

import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;
import org.apache.http.conn.util.InetAddressUtils;

import com.ghostflying.groundstation.ControlNetworkService.debugInfoFramClass;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends FragmentActivity implements Callback  {

	/**
	 * The {@link android.support.v4.view.PagerAdapter} that will provide
	 * fragments for each of the sections. We use a
	 * {@link android.support.v4.app.FragmentPagerAdapter} derivative, which
	 * will keep every loaded fragment in memory. If this becomes too memory
	 * intensive, it may be best to switch to a
	 * {@link android.support.v4.app.FragmentStatePagerAdapter}.
	 */
	SectionsPagerAdapter mSectionsPagerAdapter;

	/**
	 * The {@link ViewPager} that will host the section contents.
	 */
	ViewPager mViewPager;

	static ControlNetworkService ControlNetwork = null;
	NetworkService mNetwork = null;
	private static Maps_implements maps_implements = null;
	Canvas mcanvas = null;
	private SurfaceHolder mSurfaceHolder = null;
	private SurfaceView mSurfaceView = null;
	private Bitmap mbitmap = null;
	private static GoogleMap mMap;
	private static LocationClient mLocationClient;	
	
	private String title;
	private MapsControlFragment mMapsControlFragment = null;

	/*private EditText edit_systime = null;
	private EditText edit_roll = null;
	private EditText edit_pitch = null;
	private EditText edit_yaw = null;
	private EditText edit_vx = null;
	private EditText edit_vy = null;
	private EditText edit_vz = null;
	private EditText edit_dx = null;
	private EditText edit_dy = null;
	private EditText edit_dfi = null;
	private EditText edit_x = null;
	private EditText edit_y = null;
	private EditText edit_z = null;
	private EditText edit_rollgps = null;
	private EditText edit_yawgps = null;
	private EditText edit_pitchgps = null;
	private EditText edit_vxgps = null;
	private EditText edit_vygps = null;
	private EditText edit_vzgps = null;
	private EditText edit_xgps = null;
	private EditText edit_ygps = null;
	private EditText edit_zgps = null;
	private EditText edit_pdop = null;
	private EditText edit_p_x = null;
	private EditText edit_i_x = null;
	private EditText edit_d_x = null;
	private EditText edit_p_vx = null;
	private EditText edit_i_vx = null;
	private EditText edit_d_vx = null;
	private EditText edit_p_pitch = null;
	private EditText edit_i_pitch = null;
	private EditText edit_d_pitch = null;
	private EditText edit_p_y = null;
	private EditText edit_i_y = null;
	private EditText edit_d_y = null;
	private EditText edit_p_vy = null;
	private EditText edit_i_vy = null;
	private EditText edit_d_vy = null;
	private EditText edit_p_roll = null;
	private EditText edit_i_roll = null;
	private EditText edit_d_roll = null;
	private EditText edit_p_yaw = null;
	private EditText edit_i_yaw = null;
	private EditText edit_d_yaw = null;
	private EditText edit_p_z = null;
	private EditText edit_i_z = null;
	private EditText edit_d_z = null;
	private EditText edit_p_vz = null;
	private EditText edit_i_vz = null;
	private EditText edit_d_vz = null;*/
	private static EditText edit_debug_time = null;
	private static EditText edit_debug_reserved = null;
	private static EditText edit_debug_infotype = null;
	private static EditText edit_debug_rcc = null;
	private static EditText edit_debug_rcr = null;
	private static EditText edit_debug_rcp = null;
	private static EditText edit_debug_rcy = null;
	private static EditText edit_debug_rct = null;
	private static EditText edit_debug_pxset = null;
	private static EditText edit_debug_pyset = null;
	private static EditText edit_debug_pzset = null;
	private static EditText edit_debug_vxset = null;
	private static EditText edit_debug_vyset = null;
	private static EditText edit_debug_vzset = null;
	private static EditText edit_debug_axset = null;
	private static EditText edit_debug_ayset = null;
	private static EditText edit_debug_azset = null;
	private static EditText edit_debug_param1 = null;
	private static EditText edit_debug_param2 = null;
	private static EditText edit_debug_param3 = null;
	private static EditText edit_debug_param4 = null;
	private static EditText edit_debug_param5 = null;
	private static EditText edit_debug_param6 = null;
	private static EditText edit_debug_param7 = null;
	private static EditText edit_debug_param8 = null;
	private static ProgressBar edit_debug_servo1 = null;
	private static ProgressBar edit_debug_servo2 = null;
	private static ProgressBar edit_debug_servo3 = null;
	private static ProgressBar edit_debug_servo4 = null;
	private static ProgressBar edit_debug_servo5 = null;
	private static ProgressBar edit_debug_servo6 = null;
	private static ProgressBar edit_debug_servo7 = null;
	private static ProgressBar edit_debug_servo8 = null;
	private static TextView servo_value1 = null;
	private static TextView servo_value2 = null;
	private static TextView servo_value3 = null;
	private static TextView servo_value4 = null;
	private static TextView servo_value5 = null;
	private static TextView servo_value6 = null;
	
	
	private static TextView ip_now = null;
	private static TextView network_q = null;
	private Button button_save = null;
	private static Button button_debug_map = null;
	private static Button button_fly_visible = null;
	private static Button button_drag_fly = null;
	private static ListView fly_list = null;
	public static ArrayList<Marker> fly_point_marker = new ArrayList<Marker>();
	private static final String[] spinItems = {"Nothing","Roll","Yaw","Pitch","Vx_b","Vy_b","Vz_b"};
	private static Spinner spinner;  
    private static ArrayAdapter<String> adapter;  
    private static LinearLayout linearView = null;
    private static XYSeries series = null;
    private static GraphicalView mGraphicalView = null;
    private static XYMultipleSeriesRenderer mRenderer = null;
    private static int selectChart;
    private static ArrayList<HashMap<String,Object>> debugInfoStore = new ArrayList<HashMap<String,Object>>();

	private static Context mcontext = null;
	
	
	public static final int MESSAGE_BYTE = 0;
	public static final int EXIT = -1;
	public static final int FLYSTATUS_MESSAGE = 1;
	public static final int PID_PARAMS_MESSAGE = 2;
	public static final int DEBUG_INFO_MESSAGE = 3;
	public static final int CONTROL_DISCONNECTED = 4;
	public static final int CONTROL_CONNECTED = 5;
	public static final int VIDEO_BYTE_REC = 10;
	public static final int VIDEO_DISCONNECTED = 11;
	public static final int VIDEO_CONNECTED = 12;
	public static final int UPLOAD_TAG_NONE = 0;
	public static final int UPLOAD_TAG_PENDING = 1;
	public static final int UPLOAD_TAG_DONE = 2;

	private static String TAG = "Main";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		// Create the adapter that will return a fragment for each of the three
		// primary sections of the app.
		mSectionsPagerAdapter = new SectionsPagerAdapter(
				getSupportFragmentManager());

		// Set up the ViewPager with the sections adapter.
		mViewPager = (ViewPager) findViewById(R.id.pager);
		mViewPager.setAdapter(mSectionsPagerAdapter);
		mcontext = this;
		title = getTitle().toString();
		setTitle(title + getString(R.string.title_control_disconnected) + getString(R.string.title_video_disconnected) );
		initNetwork();

		// mMap.setOnMapLongClickListener(this);

		/*
		 * TimerTask task = new TimerTask(){ public void run(){ initMaps(); } };
		 * 
		 * Timer timer = new Timer(); timer.schedule(task, 5000);
		 */

	}

	private void initNetwork() {
		mNetwork=new NetworkService(this,mhandler);
		mNetwork.StartListen(5173);
		ControlNetwork = new ControlNetworkService(this, mhandler);
		ControlNetwork.StartListen(6666);

	}

	private final Handler mhandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case EXIT:
				finish();
			case FLYSTATUS_MESSAGE:
				//update_flystatus((flyStatusFramClass) msg.obj);
				break;
			case DEBUG_INFO_MESSAGE:
				update_debug_info((HashMap<String,Object>) msg.obj);
				break;
			case VIDEO_BYTE_REC:
				byte[] readBuf = (byte[]) msg.obj;
				int length = msg.arg1;
				dramCan(readBuf, length);				
				//Log.e(TAG, "dram a frame." + Integer.toString(length));
				break;
			case VIDEO_DISCONNECTED:
				if (ControlNetwork.getState() == ControlNetworkService.STATE_CONNECTED){
					setTitle(title + getString(R.string.title_control_connected) + getString(R.string.title_video_disconnected));	
				}
				else{
					setTitle(title + getString(R.string.title_control_disconnected) + getString(R.string.title_video_disconnected));
				}
				break;
			case VIDEO_CONNECTED:
				if (ControlNetwork.getState() == ControlNetworkService.STATE_CONNECTED){
					setTitle(title + getString(R.string.title_control_connected) + getString(R.string.title_video_connected));	
				}
				else{
					setTitle(title + getString(R.string.title_control_disconnected) + getString(R.string.title_video_connected));
				}
				break;		
			case CONTROL_CONNECTED:
				if (mNetwork.getState() == NetworkService.STATE_CONNECTED){
					setTitle(title + getString(R.string.title_control_connected) + getString(R.string.title_video_connected));						
				}
				else {
					setTitle(title + getString(R.string.title_control_connected) + getString(R.string.title_video_disconnected));
				}
				break;
			case CONTROL_DISCONNECTED:
				if (mNetwork.getState() == NetworkService.STATE_CONNECTED){
					setTitle(title + getString(R.string.title_control_disconnected) + getString(R.string.title_video_connected));						
				}
				else {
					setTitle(title + getString(R.string.title_control_disconnected) + getString(R.string.title_video_disconnected));
				}
				break;

			}
		}

	};

	private void update_debug_info(HashMap<String,Object> result) {
		// TODO Auto-generated method stub
/*		if (edit_systime == null) {
			initView();
		}*/
		//debugInfoStore.add(result);
			
/*		edit_debug_time.setText(Double.toString(result.logtime / 1000.0));
		edit_debug_reserved.setText(Short.toString(result.reserved));
		edit_debug_infotype.setText(Integer.toString(result.infotype));
		edit_debug_rcc.setText(Double.toString(result.rcc / 1000.0));
		edit_debug_rcr.setText(Double.toString(result.rcr / 1000.0));
		edit_debug_rcp.setText(Double.toString(result.rcp / 1000.0));
		edit_debug_rcy.setText(Double.toString(result.rcy / 1000.0));
		edit_debug_rct.setText(Double.toString(result.rct / 1000.0));
		edit_debug_pxset.setText(Double.toString((result.pxset / 1000.0)* 180.0 / Math.PI) );		
		edit_debug_pyset.setText(Double.toString((result.pyset / 1000.0)* 180.0 / Math.PI));
		edit_debug_pzset.setText(Double.toString(result.pzset / 1000.0));
		edit_debug_vxset.setText(Double.toString(result.vxset / 1000.0));
		edit_debug_vyset.setText(Double.toString(result.vyset / 1000.0));
		edit_debug_vzset.setText(Double.toString((result.vzset / 1000.0)* 180.0 / Math.PI));
		edit_debug_axset.setText(Double.toString(result.axset / 1000.0));
		edit_debug_ayset.setText(Double.toString(result.ayset / 1000.0));
		edit_debug_azset.setText(Double.toString(result.azset / 1000.0));
		edit_debug_param1.setText(Double.toString(result.param[0] / 1000.0));
		edit_debug_param2.setText(Double.toString(result.param[1] / 1000.0));
		edit_debug_param3.setText(Double.toString(result.param[2] / 1000.0));
		edit_debug_param4.setText(Double.toString(result.param[3] / 1000.0));
		edit_debug_param5.setText(Double.toString(result.param[4] / 1000.0));
		edit_debug_param6.setText(Double.toString(result.param[5] / 1000.0));
		edit_debug_param7.setText(Double.toString(result.param[6] / 1000.0));
		edit_debug_param8.setText(Double.toString(result.param[7] / 1000.0));
		edit_debug_servo1.setProgress(result.serveout[0] - 1000);
		edit_debug_servo2.setProgress(result.serveout[1] - 1000);
		edit_debug_servo3.setProgress(result.serveout[2] - 1000);
		edit_debug_servo4.setProgress(result.serveout[3] - 1000);
		edit_debug_servo5.setProgress(result.serveout[4] - 1000);
		edit_debug_servo6.setProgress(result.serveout[5] - 1000);
		servo_value1.setText(Integer.toString(result.serveout[0]));
		servo_value2.setText(Integer.toString(result.serveout[1]));
		servo_value3.setText(Integer.toString(result.serveout[2]));
		servo_value4.setText(Integer.toString(result.serveout[3]));
		servo_value5.setText(Integer.toString(result.serveout[4]));
		servo_value6.setText(Integer.toString(result.serveout[5]));
		if (series != null){
			addpoint(result.logtime/1000.0,50.0);
		}*/
		
		
		edit_debug_time.setText(Double.toString((Double) result.get("logtime")));
		edit_debug_reserved.setText(Short.toString((Short) result.get("reserved")));
		edit_debug_infotype.setText(Integer.toString((Integer) result.get("infotype")));
		edit_debug_rcc.setText(Double.toString((Double) result.get("rcc")));
		edit_debug_rcr.setText(Double.toString((Double) result.get("rcr")));
		edit_debug_rcp.setText(Double.toString((Double) result.get("rcp")));
		edit_debug_rcy.setText(Double.toString((Double) result.get("rcy")));
		edit_debug_rct.setText(Double.toString((Double) result.get("rct")));
		edit_debug_pxset.setText(Double.toString((Double) result.get("pxset")) );		
		edit_debug_pyset.setText(Double.toString((Double) result.get("pyset")));
		edit_debug_pzset.setText(Double.toString((Double) result.get("pzset")));
		edit_debug_vxset.setText(Double.toString((Double) result.get("vxset")));
		edit_debug_vyset.setText(Double.toString((Double) result.get("vyset")));
		edit_debug_vzset.setText(Double.toString((Double) result.get("vzset")));
		edit_debug_axset.setText(Double.toString((Double) result.get("axset")));
		edit_debug_ayset.setText(Double.toString((Double) result.get("ayset")));
		edit_debug_azset.setText(Double.toString((Double) result.get("azset")));
		edit_debug_param1.setText(Double.toString((Double) result.get("param0")));
		edit_debug_param2.setText(Double.toString((Double) result.get("param1")));
		edit_debug_param3.setText(Double.toString((Double) result.get("param2")));
		edit_debug_param4.setText(Double.toString((Double) result.get("param3")));
		edit_debug_param5.setText(Double.toString((Double) result.get("param4")));
		edit_debug_param6.setText(Double.toString((Double) result.get("param5")));
		edit_debug_param7.setText(Double.toString((Double) result.get("param6")));
		edit_debug_param8.setText(Double.toString((Double) result.get("param7")));
		edit_debug_servo1.setProgress((Integer)result.get("serve0") - 1000);
		edit_debug_servo2.setProgress((Integer)result.get("serve1") - 1000);
		edit_debug_servo3.setProgress((Integer)result.get("serve2") - 1000);
		edit_debug_servo4.setProgress((Integer)result.get("serve3") - 1000);
		edit_debug_servo5.setProgress((Integer)result.get("serve4") - 1000);
		edit_debug_servo6.setProgress((Integer)result.get("serve5") - 1000);
		servo_value1.setText(Integer.toString((Integer)result.get("serve0")));
		servo_value2.setText(Integer.toString((Integer)result.get("serve1")));
		servo_value3.setText(Integer.toString((Integer)result.get("serve2")));
		servo_value4.setText(Integer.toString((Integer)result.get("serve3")));
		servo_value5.setText(Integer.toString((Integer)result.get("serve4")));
		servo_value6.setText(Integer.toString((Integer) result.get("serve5")));
		if (series != null){
			switch (selectChart){
			case 1:
				addpoint((Double)result.get("logtime"),(Double) result.get("pxset"));
				break;
			case 2:
				addpoint((Double)result.get("logtime"),(Double) result.get("vzset"));
				break;
			case 3:
				addpoint((Double)result.get("logtime"),(Double) result.get("pyset"));
				break;
			}			
		}
		debugInfoStore.add(result);

	}



/*	protected void update_flystatus(flyStatusFramClass result) {
		// TODO Auto-generated method stub
		if (edit_systime == null) {
			initView();
		}
		edit_systime.setText(Double.toString(result.logtime / 1000.0));
		edit_roll.setText(Double.toString(result.roll / 1000.0));
		edit_pitch.setText(Double.toString(result.pitch / 1000.0));
		edit_yaw.setText(Double.toString(result.yaw / 1000.0));
		edit_x.setText(Double.toString(result.x / 1000.0));
		edit_y.setText(Double.toString(result.y / 1000.0));
		edit_z.setText(Double.toString(result.z / 1000.0));
		edit_dx.setText(Integer.toString(result.dx));
		edit_dy.setText(Integer.toString(result.dy));
		edit_dfi.setText(Integer.toString(result.dfi));
		edit_vx.setText(Double.toString(result.vx / 1000.0));
		edit_vy.setText(Double.toString(result.vy / 1000.0));
		edit_vz.setText(Double.toString(result.vz / 1000.0));
		edit_rollgps.setText(Double.toString(result.roll_gps / 1000.0));
		edit_yawgps.setText(Double.toString(result.yaw_gps / 1000.0));
		edit_pitchgps.setText(Double.toString(result.pitch_gps / 1000.0));
		edit_vxgps.setText(Double.toString(result.vx_gps / 1000.0));
		edit_vygps.setText(Double.toString(result.vy_gps / 1000.0));
		edit_vzgps.setText(Double.toString(result.vz_gps / 1000.0));
		edit_xgps.setText(Double.toString(result.x_gps / 1000.0));
		edit_ygps.setText(Double.toString(result.y_gps / 1000.0));
		edit_zgps.setText(Double.toString(result.z_gps / 1000.0));
		edit_pdop.setText(Integer.toString(result.pdop / 1000));

	}*/

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	public static class MapsMainFragment extends Fragment {
		public MapsMainFragment() {

		}

		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {

			View rootView = inflater.inflate(R.layout.maps_fragment_view,
					container, false);
			
			return rootView;

		}

	}
	
	

	public static class MapPageFragment extends SupportMapFragment{
	    @Override
	    public void onViewCreated(View view, Bundle savedInstanceState) {
	        super.onViewCreated(view, savedInstanceState);
	        if (mMap == null) {
				mMap = ((SupportMapFragment) getFragmentManager()
						.findFragmentById(R.id.maps_main_fragment))
						.getMap();
				// Check if we were successful in obtaining the map.
				if (mMap != null) {
					Toast.makeText(mcontext, getString(R.string.toast_success_map_initial), Toast.LENGTH_SHORT).show();
					maps_implements = new Maps_implements(mMap);
					mMap.setMyLocationEnabled(true);					
					mMap.setOnMapLongClickListener(maps_implements);
					mMap.setOnInfoWindowClickListener(maps_implements);
					if (mLocationClient == null){
						mLocationClient = new LocationClient(getActivity(), maps_implements, maps_implements);
					}				
					
					
					if (!mLocationClient.isConnected()){
						mLocationClient.connect();			
					}
					// The Map is verified. It is now safe to manipulate
					// the map.

				}
			}
	    }
		
	}
	

	public static class MapsControlFragment extends Fragment {
		static final int MAP_MESSAGE_INFOWINDOW_CLICK = 1;
		static final int MAP_MESSAGE_MARKER_DRAG = 2;
		private boolean change_fly_point_flag = false;
		private Marker marker_now = null;
		Location mCurrentLocation;
		
		
		
		ArrayList<HashMap<String, Object>> mylist = new ArrayList<HashMap<String, Object>>();
		FlyPointListAdapter mSchedule = new FlyPointListAdapter(mcontext, mylist);

		public MapsControlFragment() {
		}
		
		private void map_initial(){
			if (mMap == null) {
				mMap = ((SupportMapFragment) getFragmentManager()
						.findFragmentById(R.id.maps_main_fragment))
						.getMap();
				// Check if we were successful in obtaining the map.
				if (mMap != null) {
					Toast.makeText(mcontext, getString(R.string.toast_success_map_initial), Toast.LENGTH_SHORT).show();
					maps_implements = new Maps_implements(mMap,maphandler);
					mMap.setMyLocationEnabled(true);					
					mMap.setOnMapLongClickListener(maps_implements);
					mMap.setOnInfoWindowClickListener(maps_implements);
					if (mLocationClient == null){
						mLocationClient = new LocationClient(getActivity(), maps_implements, maps_implements);
					}				
					
					
					if (!mLocationClient.isConnected()){
						mLocationClient.connect();
						return;						
					}
					// The Map is verified. It is now safe to manipulate
					// the map.

				}
			}
			else {
				maps_implements.setup_handler(maphandler);
			}
		}
		
		private void fly_list_initial() {
			map_initial();
			if (!mLocationClient.isConnected()) {
				Toast.makeText(mcontext,
						getString(R.string.toast_wait_for_connect),
						Toast.LENGTH_SHORT).show();
				return;
			}
			Marker temp;

			/*
			 * GoogleMapOptions options = new GoogleMapOptions();
			 * options.mapType(GoogleMap.MAP_TYPE_NORMAL)
			 * .compassEnabled(true).rotateGesturesEnabled(true)
			 * .tiltGesturesEnabled(true);
			 */

			
			mCurrentLocation = mLocationClient.getLastLocation();
			LatLng latLng = new LatLng(mCurrentLocation.getLatitude(),
					mCurrentLocation.getLongitude());
			// mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

			mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 14));
			temp = mMap.addMarker(new MarkerOptions().position(new LatLng(
					mCurrentLocation.getLatitude() + 0.015, mCurrentLocation
							.getLongitude() - 0.021)));
			fly_point_marker.add(temp);
			temp = mMap.addMarker(new MarkerOptions().position(new LatLng(
					mCurrentLocation.getLatitude() + 0.011, mCurrentLocation
							.getLongitude() - 0.021)));
			fly_point_marker.add(temp);
			temp = mMap.addMarker(new MarkerOptions().position(new LatLng(
					mCurrentLocation.getLatitude() + 0.007, mCurrentLocation
							.getLongitude() - 0.021)));
			fly_point_marker.add(temp);
			temp = mMap.addMarker(new MarkerOptions().position(new LatLng(
					mCurrentLocation.getLatitude() + 0.003, mCurrentLocation
							.getLongitude() - 0.021)));
			fly_point_marker.add(temp);
			temp = mMap.addMarker(new MarkerOptions().position(new LatLng(
					mCurrentLocation.getLatitude() + 0.011, mCurrentLocation
							.getLongitude() - 0.018)));
			fly_point_marker.add(temp);
			temp = mMap.addMarker(new MarkerOptions().position(new LatLng(
					mCurrentLocation.getLatitude() + 0.007, mCurrentLocation
							.getLongitude() - 0.015)));
			fly_point_marker.add(temp);
			temp = mMap.addMarker(new MarkerOptions().position(new LatLng(
					mCurrentLocation.getLatitude() + 0.015, mCurrentLocation
							.getLongitude() - 0.012)));
			fly_point_marker.add(temp);
			temp = mMap.addMarker(new MarkerOptions().position(new LatLng(
					mCurrentLocation.getLatitude() + 0.011, mCurrentLocation
							.getLongitude() - 0.012)));
			fly_point_marker.add(temp);
			temp = mMap.addMarker(new MarkerOptions().position(new LatLng(
					mCurrentLocation.getLatitude() + 0.007, mCurrentLocation
							.getLongitude() - 0.012)));
			fly_point_marker.add(temp);
			temp = mMap.addMarker(new MarkerOptions().position(new LatLng(
					mCurrentLocation.getLatitude() + 0.003, mCurrentLocation
							.getLongitude() - 0.012)));
			fly_point_marker.add(temp);
			// above the "N"
			temp = mMap.addMarker(new MarkerOptions().position(new LatLng(
					mCurrentLocation.getLatitude() + 0.009, mCurrentLocation
							.getLongitude() - 0.006)));
			fly_point_marker.add(temp);
			temp = mMap.addMarker(new MarkerOptions().position(new LatLng(
					mCurrentLocation.getLatitude() + 0.003, mCurrentLocation
							.getLongitude() + 0.00)));
			fly_point_marker.add(temp);
			temp = mMap.addMarker(new MarkerOptions().position(new LatLng(
					mCurrentLocation.getLatitude() + 0.015, mCurrentLocation
							.getLongitude() + 0.00)));
			fly_point_marker.add(temp);
			temp = mMap.addMarker(new MarkerOptions().position(new LatLng(
					mCurrentLocation.getLatitude() + 0.013, mCurrentLocation
							.getLongitude() - 0.004)));
			fly_point_marker.add(temp);
			temp = mMap.addMarker(new MarkerOptions().position(new LatLng(
					mCurrentLocation.getLatitude() + 0.005, mCurrentLocation
							.getLongitude() - 0.004)));
			fly_point_marker.add(temp);
			temp = mMap.addMarker(new MarkerOptions().position(new LatLng(
					mCurrentLocation.getLatitude() + 0.005, mCurrentLocation
							.getLongitude() + 0.004)));
			fly_point_marker.add(temp);
			temp = mMap.addMarker(new MarkerOptions().position(new LatLng(
					mCurrentLocation.getLatitude() + 0.009, mCurrentLocation
							.getLongitude() + 0.004)));
			fly_point_marker.add(temp);
			temp = mMap.addMarker(new MarkerOptions().position(new LatLng(
					mCurrentLocation.getLatitude() + 0.009, mCurrentLocation
							.getLongitude() + 0.002)));
			fly_point_marker.add(temp);
			temp = mMap.addMarker(new MarkerOptions().position(new LatLng(
					mCurrentLocation.getLatitude() + 0.009, mCurrentLocation
							.getLongitude() + 0.006)));
			fly_point_marker.add(temp);
			temp = mMap.addMarker(new MarkerOptions().position(new LatLng(
					mCurrentLocation.getLatitude() + 0.003, mCurrentLocation
							.getLongitude() + 0.004)));
			fly_point_marker.add(temp);
			// above the "G"
			temp = mMap.addMarker(new MarkerOptions().position(new LatLng(
					mCurrentLocation.getLatitude() + 0.009, mCurrentLocation
							.getLongitude() + 0.011)));
			fly_point_marker.add(temp);
			temp = mMap.addMarker(new MarkerOptions().position(new LatLng(
					mCurrentLocation.getLatitude() + 0.003, mCurrentLocation
							.getLongitude() + 0.017)));
			fly_point_marker.add(temp);
			temp = mMap.addMarker(new MarkerOptions().position(new LatLng(
					mCurrentLocation.getLatitude() + 0.015, mCurrentLocation
							.getLongitude() + 0.017)));
			fly_point_marker.add(temp);
			temp = mMap.addMarker(new MarkerOptions().position(new LatLng(
					mCurrentLocation.getLatitude() + 0.005, mCurrentLocation
							.getLongitude() + 0.013)));
			fly_point_marker.add(temp);
			temp = mMap.addMarker(new MarkerOptions().position(new LatLng(
					mCurrentLocation.getLatitude() + 0.013, mCurrentLocation
							.getLongitude() + 0.013)));
			fly_point_marker.add(temp);
			temp = mMap.addMarker(new MarkerOptions().position(new LatLng(
					mCurrentLocation.getLatitude() + 0.005, mCurrentLocation
							.getLongitude() + 0.021)));
			fly_point_marker.add(temp);
			temp = mMap.addMarker(new MarkerOptions().position(new LatLng(
					mCurrentLocation.getLatitude() + 0.013, mCurrentLocation
							.getLongitude() + 0.021)));
			fly_point_marker.add(temp);
			// above the "C"
			for (int i = 0; i < fly_point_marker.size(); i++) {
				fly_point_marker.get(i)
						.setTitle(
								getString(R.string.map_fly_point)
										+ Integer.toString(i));
			}

			inital_fly_point_view();

			// mLocationClient.disconnect();

			/*
			 * final LatLng MELBOURNE = new LatLng(-37.81319, 144.96298); Marker
			 * melbourne = mMap.addMarker(new MarkerOptions()
			 * .position(MELBOURNE) .title("Melbourne")
			 * .snippet("Population: 4,137,400"));
			 */
			// mMap.setOnMapLongClickListener(add_fly_point());
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			final View rootView = inflater.inflate(R.layout.maps_control_view,
					container, false);
			button_debug_map = (Button) rootView.findViewById(R.id.map_debug);
			button_drag_fly = (Button)rootView.findViewById(R.id.drag);
			button_fly_visible = (Button)rootView.findViewById(R.id.fly_visible);
			fly_list = (ListView) rootView.findViewById(R.id.flypoint_list);


			for (int i = 0; i < 10; i++) {//fake date
				HashMap<String, Object> map = new HashMap<String, Object>();
				map.put("title",i);
				map.put("latitude", i);
				map.put("longitude", i);
				map.put("high", i);
				map.put("uploadtag", UPLOAD_TAG_NONE);
				if (i < 5) {
					map.put("Status", true);
				} else {
					map.put("Status", false);
				}

				mylist.add(map);
			}
			
			fly_list.setAdapter(mSchedule);
			fly_list.setOnItemClickListener(new OnItemClickListener(){

				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,
						int position, long arg3) {
					// TODO Auto-generated method stub
					if (change_fly_point_flag){
						update_fly_point_view(position,marker_now);
						Toast.makeText(mcontext, getString(R.string.toast_success_update_fly_part1)+Integer.toString(position)+getString(R.string.toast_success_update_fly_part2), Toast.LENGTH_SHORT).show();
						change_fly_point_flag = false;
					}
					else {
						mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(fly_point_marker.get(position).getPosition(),14));
						fly_point_marker.get(position).setVisible(true);
						fly_point_marker.get(position).showInfoWindow();
					}					
					Log.i("testy", "I Clicked on Row " + position + " and it worked!");
					
				}
				
			});
			
			fly_list.setOnItemLongClickListener(new OnItemLongClickListener(){

				@Override
				public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
						int position, long arg3) {
					// TODO Auto-generated method stub
					//Toast.makeText(getActivity(), "PLease long press the flypoint "+Integer.toString(position), Toast.LENGTH_SHORT).show();
					//getActivity().startActivity(new Intent(mcontext,PopupActivity.class));
					Intent mIntent = new Intent(mcontext,PopupActivity.class);
					mIntent.putExtra("high", (Integer)mylist.get(position).get("high"));
					mIntent.putExtra("position", position);
					getActivity().startActivityForResult(mIntent, position);					
					Log.i("testy", "I Long  Clicked on Row " + position + " and it worked!");
					return false;
				}
				
			});
			
			button_drag_fly.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if (fly_point_marker.size() < 1){
						Toast.makeText(mcontext, getString(R.string.toast_fly_point_no_initial), Toast.LENGTH_SHORT).show();
						return;
					}
					map_initial();
					if (button_drag_fly.getText() == getString(R.string.button_drag)){
						for (int i=0;i<fly_point_marker.size();i++){
							fly_point_marker.get(i).setDraggable(true);
							fly_point_marker.get(i).setVisible(true);
							mMap.setOnMarkerDragListener(maps_implements);
							mMap.setOnMapLongClickListener(null);
							button_drag_fly.setText(getString(R.string.button_drag_off));
						}
					}
					else {
						for (int i=0;i<fly_point_marker.size();i++){
							fly_point_marker.get(i).setDraggable(false);
						}
						mMap.setOnMapLongClickListener(maps_implements);
						button_drag_fly.setText(getString(R.string.button_drag));
					}

					
				}
				
			});
			
			

			button_fly_visible.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if (fly_point_marker.isEmpty()){
						Toast.makeText(mcontext, getString(R.string.toast_fly_point_no_initial), Toast.LENGTH_SHORT).show();
						return;
					}
					map_initial();
					if (button_fly_visible.getText() == getString(R.string.button_visible_off)){
						for (int i=0;i<fly_point_marker.size();i++){						
							fly_point_marker.get(i).setVisible(false);						
						}
						button_fly_visible.setText(getString(R.string.button_visible_on));
					}
					else if (button_fly_visible.getText() == getString(R.string.button_visible_on)){
						for (int i=0;i<fly_point_marker.size();i++){						
							fly_point_marker.get(i).setVisible(true);						
						}
						button_fly_visible.setText(getString(R.string.button_visible_off));
					}
					
				}
				
			});
			



			button_debug_map.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					fly_list_initial();
					button_debug_map.setEnabled(false);
				}

			});
			


			

			return rootView;
		}
		

		


		public Handler maphandler = new Handler(){
			public void handleMessage(Message msg){
				switch (msg.what){
				case MAP_MESSAGE_INFOWINDOW_CLICK:
					marker_now = (Marker) msg.obj;
					change_fly_point_flag = true;					
					Toast.makeText(mcontext, getString(R.string.toast_click_the_infowindow),Toast.LENGTH_SHORT).show();
					break;
				case MAP_MESSAGE_MARKER_DRAG:
					int t = (Integer) msg.obj;
					update_fly_point_view(t);
				
				}
			}
		};

		protected void inital_fly_point_view() {
			// TODO Auto-generated method stub

			//DecimalFormat df = new DecimalFormat(".###");

			for (int i = 0; i < fly_point_marker.size(); i++) {
				HashMap<String, Object> map = new HashMap<String, Object>();
/*				map.put("title",
						getString(R.string.map_fly_point) + Integer.toString(i));
				map.put("location",
						getString(R.string.map_latitude)
								+ df.format(fly_point_marker[i].getPosition().latitude)
								+ getString(R.string.map_longitude)
								+ df.format(fly_point_marker[i].getPosition().longitude)
								+ getString(R.string.map_high)
								+ "5");
				map.put("Status", false);*/
				map.put("title", i);
				map.put("latitude", fly_point_marker.get(i).getPosition().latitude);
				map.put("longitude", fly_point_marker.get(i).getPosition().longitude);
				map.put("high", 5);
				map.put("Status", false);
				map.put("uploadtag", UPLOAD_TAG_NONE);
				if (i<mylist.size()){
					mylist.set(i, map);
				}
				else {
					mylist.add(map);
				}
			}

			mSchedule.notifyDataSetChanged();
		}

		protected void update_fly_point_view(int position, Marker marker){
			//DecimalFormat df=new DecimalFormat(".###");
			fly_point_marker.get(position).setPosition(marker.getPosition());
			HashMap<String, Object> map = new HashMap<String, Object>();
			/*map.put("title", getString(R.string.map_fly_point)  + Integer.toString(position));
			map.put("Status", false);
			map.put("location", getString(R.string.map_latitude)+df.format(marker.getPosition().latitude)+getString(R.string.map_longitude)+df.format(marker.getPosition().longitude));*/
			//map.put("title", position);
			map.put("latitude", marker.getPosition().latitude);
			map.put("longitude", marker.getPosition().longitude);
			map.put("high", mylist.get(position).get("high"));
			map.put("Status", false);
			map.put("uploadtag", mylist.get(position).get("uploadtag"));
			mylist.set(position, map);
			mSchedule.notifyDataSetChanged();
		}
		
		protected void update_fly_point_view(int position){
			//DecimalFormat df=new DecimalFormat(".###");
			//fly_point_marker[position].setPosition(marker.getPosition());
			HashMap<String, Object> map = mylist.get(position);
/*			map.put("ItemTitle", "Flypoint:" + Integer.toString(position));
			map.put("Status", false);*/
			//map.put("location", getString(R.string.map_latitude)+df.format(fly_point_marker[position].getPosition().latitude)+getString(R.string.map_longitude)+df.format(fly_point_marker[position].getPosition().longitude));
			map.put("latitude", fly_point_marker.get(position).getPosition().latitude);
			map.put("longitude", fly_point_marker.get(position).getPosition().longitude);
			map.put("high", mylist.get(position).get("high"));
			map.put("Status", false);
			map.put("uploadtag", mylist.get(position).get("uploadtag"));
			mylist.set(position, map);
			mSchedule.notifyDataSetChanged();
		}
		
		public void delete_fly_point_view (int position){
			if ((Integer)mylist.get(position).get("uploadtag") == UPLOAD_TAG_DONE){
				ControlNetwork.upload_fly_point(2,mylist.get(position), mylist.size());
				//delete on the fly.
			}
			mylist.remove(position);
			fly_point_marker.get(position).remove();			
			for (int i = fly_point_marker.size() -1 ;i>position ;i--){
				fly_point_marker.get(i).setTitle(fly_point_marker.get(i-1).getTitle());
			}
			fly_point_marker.remove(position);
			mSchedule.notifyDataSetChanged();
		}
		
		public void update_fly_point_high (int position, int high){
			mylist.get(position).put("high", high);
			mSchedule.notifyDataSetChanged();
		}
		
		public void insert_fly_point(int position) {
			Marker newMarker = mMap.addMarker(new MarkerOptions()
					.position(new LatLng(mCurrentLocation.getLatitude(),
							mCurrentLocation.getLongitude())));
			fly_point_marker.add(position, newMarker);
			for (int i = position; i < fly_point_marker.size(); i++) {
				fly_point_marker.get(i)
						.setTitle(
								getString(R.string.map_fly_point)
										+ Integer.toString(i));
			}
			newMarker.showInfoWindow();
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("longitude", newMarker.getPosition().longitude);
			map.put("latitude", newMarker.getPosition().latitude);
			map.put("high", 5);
			map.put("Status", false);
			map.put("uploadtag", UPLOAD_TAG_NONE);
			mylist.add(position, map);
			mSchedule.notifyDataSetChanged();
		}
		
		public void upload_fly_point(int position){
			if ((Integer)mylist.get(position).get("uploadtag") != UPLOAD_TAG_DONE ){
				ControlNetwork.upload_fly_point(1,mylist.get(position), mylist.size());
			}
			else {
				ControlNetwork.upload_fly_point(3,mylist.get(position), mylist.size());
			}	
			mylist.get(position).put("uploadtag", UPLOAD_TAG_PENDING);
			mSchedule.notifyDataSetChanged();
		};
		


		public class FlyPointListAdapter extends BaseAdapter {
			private LayoutInflater mInflater;
			private ArrayList<HashMap<String, Object>> mData;
			DecimalFormat df=new DecimalFormat(".###");

			public FlyPointListAdapter(Context context,
					ArrayList<HashMap<String, Object>> data) {
				this.mInflater = LayoutInflater.from(context);
				mData = data;
			}

			public int getCount() {
				// TODO Auto-generated method stub
				return mData.size();
			}

			public Object getItem(int arg0) {
				// TODO Auto-generated method stub
				return mData.get(arg0);
			}

			public long getItemId(int arg0) {
				// TODO Auto-generated method stub
				return arg0;
			}

			public View getView(int position, View convertView, ViewGroup parent) {
				ViewHolder holder = null;
				if (convertView == null) {
					holder = new ViewHolder();
					convertView = mInflater.inflate(
							R.layout.flypoint_list_view, null);
					holder.title = (TextView) convertView
							.findViewById(R.id.title);
					holder.location = (TextView) convertView
							.findViewById(R.id.location);
					convertView.setTag(holder);
				} else {
					holder = (ViewHolder) convertView.getTag();
				}

/*				holder.location.setText((String) mData.get(position).get(
						"location"));*/
/*				holder.title.setText((String) mData.get(position).get(
						"title"));*/
				holder.title.setText(getString(R.string.map_fly_point)  + Integer.toString(position));
				holder.location.setText(getString(R.string.map_latitude)
												+ df.format(mData.get(position).get("latitude"))
												+ getString(R.string.map_longitude)
												+ df.format(mData.get(position).get("longitude"))
												+ getString(R.string.map_high)
												+ String.valueOf((mData.get(position).get("high"))));
/*				holder.location.setText(getString(R.string.map_latitude)
												+ df.format(mData.get(position).get("latitude")));*/


/*				if ((Boolean) mData.get(position).get("uploadtag")) {
					convertView.setBackgroundColor(Color.YELLOW);
				} else {
					convertView.setBackgroundColor(Color.TRANSPARENT);
				}*/
				switch ((Integer)mData.get(position).get("uploadtag")){
				case UPLOAD_TAG_NONE:
					convertView.setBackgroundColor(Color.TRANSPARENT);
					break;
				case UPLOAD_TAG_PENDING:
					convertView.setBackgroundColor(Color.YELLOW);
					break;
				case UPLOAD_TAG_DONE:
					convertView.setBackgroundColor(Color.GREEN);
					break;
				}

				/*
				 * if (position % 2 == 0) {
				 * convertView.setBackgroundColor(Color.RED); } else {
				 * convertView.setBackgroundColor(Color.TRANSPARENT); }
				 */

				// convertView.getBackground().setAlpha(80);

				return convertView;
			}

			public void setSelectItem(int selectItem) {
				this.selectItem = selectItem;
			}

			private int selectItem = -1;
		}

		public final class ViewHolder {
			public TextView title;
			public TextView location;
		}

	}

	/**
	 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
	 * one of the sections/tabs/pages.
	 */
	public class SectionsPagerAdapter extends FragmentPagerAdapter {

		public SectionsPagerAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public Fragment getItem(int position) {
			// getItem is called to instantiate the fragment for the given page.
			// Return a DummySectionFragment (defined as a static inner class
			// below) with the page number as its lone argument.
			Fragment fragment = null;
			switch (position) {
			case 0:
			case 2:
				fragment = new DummySectionFragment();
				Bundle args = new Bundle();
				args.putInt(DummySectionFragment.ARG_SECTION_NUMBER,
						position + 1);			
				fragment.setArguments(args);
				break;
			case 1:
				fragment = new MapsMainFragment();

				// fragment = SupportMapFragment.newInstance();
				// mMap =((SupportMapFragment)fragment).getMap();
			}

			return fragment;
		}

		@Override
		public int getCount() {
			// Show 3 total pages.
			return 3;
		}

		@Override
		public CharSequence getPageTitle(int position) {
			Locale l = Locale.getDefault();
			switch (position) {
			case 0:
				return getString(R.string.title_section1).toUpperCase(l);
			case 1:
				return getString(R.string.title_section2).toUpperCase(l);
			case 2:
				return getString(R.string.title_section3).toUpperCase(l);
			}
			return null;
		}
	}
	
	
	private synchronized void addpoint (double x , double y){
		series.add(x, y);
		if (mRenderer.getXAxisMax() < (Double)debugInfoStore.get(debugInfoStore.size() -1).get("logtime")){
			mRenderer.setXAxisMax((int) (2 * Math.round((Double) debugInfoStore.get(debugInfoStore.size() -1).get("logtime"))));
		}
		mGraphicalView.invalidate();
	}
	// 折线图
	public static synchronized void lineViewInitial(int select) {
		String title = "";
		String valuekey = "logtime";
		int ymin = 0;
		int ymax = 0;
		int xmax = 0;
		
		selectChart = select;
		
		if (mGraphicalView != null){
			linearView.removeAllViews();
			mGraphicalView = null;
		}
		XYMultipleSeriesDataset mDataset = new XYMultipleSeriesDataset();
		switch (select){
		case 1:
			title = "Roll";
			ymin = -20;
			ymax = 20;
			valuekey = "pxset";
			break;
		case 2:
			title = "Yaw";
			ymin = -20;
			ymax = 20;
			valuekey = "vzset";
			break;
		case 3:
			title = "Pitch";
			ymin = -20;
			ymax = 20;
			valuekey = "pyset";
			break;			
		}
		
		xmax = (int) (2 * Math.round((Double) debugInfoStore.get(debugInfoStore.size() -1).get("logtime"))) ;
		if (xmax < 200){
			xmax = 300;
		}
		series = new XYSeries(title);
		series.add(0, 0);
		for (HashMap<String, Object> result:debugInfoStore){
			series.add((Double) result.get("logtime"),(Double) result.get(valuekey));			
		}
		
		mDataset.addSeries(series);

		mRenderer = new XYMultipleSeriesRenderer();
		// 设置图表的X轴的当前方向
		mRenderer.setOrientation(XYMultipleSeriesRenderer.Orientation.HORIZONTAL);
		mRenderer.setXTitle("Systime");// 设置为X轴的标题
		mRenderer.setYTitle(title);// 设置y轴的标题
		mRenderer.setAxisTitleTextSize(20);// 设置轴标题文本大小
		//mRenderer.setChartTitle(title);// 设置图表标题
		mRenderer.setChartTitleTextSize(30);// 设置图表标题文字的大小
		mRenderer.setLabelsTextSize(18);// 设置标签的文字大小
		mRenderer.setLegendTextSize(20);// 设置图例文本大小
		mRenderer.setPointSize(10f);// 设置点的大小
		mRenderer.setYAxisMin(ymin);// 设置y轴最小值是0
		mRenderer.setYAxisMax(ymax);
		mRenderer.setYLabels(10);// 设置Y轴刻度个数（貌似不太准确）
		mRenderer.setXAxisMin(0);
		mRenderer.setXAxisMax(xmax);
		mRenderer.setShowGrid(true);// 显示网格s
		mRenderer.setMargins(new int[] { 50, 30, 50, 20 });// 设置视图位置

		XYSeriesRenderer r = new XYSeriesRenderer();// (类似于一条线对象)
		r.setColor(Color.BLUE);// 设置颜色
		r.setPointStyle(PointStyle.POINT);// 设置点的样式
		r.setFillPoints(false);// 填充点（显示的点是空心还是实心）
		r.setDisplayChartValues(false);// 将点的值显示出来
		r.setChartValuesSpacing(10);// 显示的点的值与图的距离
		r.setChartValuesTextSize(25);// 点的值的文字大小

		// r.setFillBelowLine(true);//是否填充折线图的下方
		// r.setFillBelowLineColor(Color.GREEN);//填充的颜色，如果不设置就默认与线的颜色一致
		r.setLineWidth(2);// 设置线宽
		mRenderer.addSeriesRenderer(r);
		mRenderer.setApplyBackgroundColor(true);
		mRenderer.setMarginsColor(0x323232);
		mRenderer.setXLabelsColor(Color.BLACK);
		mRenderer.setYLabelsColor(0,Color.BLACK);
		mRenderer.setAxesColor(Color.BLACK);
		mRenderer.setLabelsColor(Color.BLACK);


		mGraphicalView = ChartFactory.getLineChartView(mcontext, mDataset,
				mRenderer);
		mGraphicalView.setBackgroundColor(Color.TRANSPARENT);
		linearView.addView(mGraphicalView);
	}

	/**
	 * A dummy fragment representing a section of the app, but that simply
	 * displays dummy text.
	 */
	public static class DummySectionFragment extends Fragment {
		/**
		 * The fragment argument representing the section number for this
		 * fragment.
		 */
		public static final String ARG_SECTION_NUMBER = "section_number";
		public DummySectionFragment() {
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			switch (getArguments().getInt(ARG_SECTION_NUMBER)) {
			case 1:			
				View sysinfo = inflater.inflate(R.layout.system_info, container, false);
				initView(sysinfo);
				linearView=(LinearLayout)sysinfo.findViewById(R.id.chart);
				adapter=new ArrayAdapter<String>(getActivity(),android.R.layout.simple_spinner_item,spinItems);
				adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				spinner.setAdapter(adapter);
		        spinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener()  
		        {  
		  
		            @Override  
		            public void onItemSelected(AdapterView<?> arg0, View arg1,  
		                    int arg2, long arg3) {  
		                // TODO Auto-generated method stub
		            	if (arg2 >0){
		            		lineViewInitial(arg2);
		            	}
		            	else {
		            		series = null;
		            	}
		                arg0.setVisibility(View.VISIBLE);  
		            }  
		  
		            @Override  
		            public void onNothingSelected(AdapterView<?> arg0) {  
		                // TODO Auto-generated method stub  
		                  
		            }  
		              
		        });
				
				//lineView(linearView,0);
				return sysinfo;
			case 3:
				View video_view = inflater.inflate(R.layout.videoview,container,false);
				ip_now = (TextView) video_view.findViewById(R.id.video_ip_now);
				//network_q = (TextView) video_view.findViewById(R.id.video_network_q);
				ip_now.setText(getLocalIpAddress());
				return video_view;			
				
			}
			View rootView = inflater.inflate(R.layout.fragment_main_dummy,
					container, false);
			TextView dummyTextView = (TextView) rootView
					.findViewById(R.id.section_label);
			dummyTextView.setText(Integer.toString(getArguments().getInt(
					ARG_SECTION_NUMBER)));
			return rootView;
		}
	}
	
	private void dramCan (byte[] buffer,int length){
		if(mSurfaceView==null ){
			mSurfaceView=(SurfaceView)findViewById(R.id.surfaceView_video);
			if (mSurfaceView!= null){
				mSurfaceView.setFocusable(true);
				mSurfaceView.setFocusableInTouchMode(true);
				mSurfaceView.setClickable(true);
				mSurfaceHolder=mSurfaceView.getHolder();
				mSurfaceHolder.addCallback(this);				
			}			
		}
		else{
			mbitmap = BitmapFactory.decodeByteArray(buffer,0,length);
			if (mbitmap!=null){
				mcanvas=mSurfaceHolder.lockCanvas();
				if (mcanvas != null){
					mcanvas.drawBitmap(mbitmap, 0, 0, null);
					mSurfaceHolder.unlockCanvasAndPost(mcanvas);	
				}				
							
			}
			else {
				Log.d(TAG, "null");
			}
		}
		mNetwork.is_frame_done = true;
	
	
		
	}

	private static void initView(View v) {// init the main view
/*		edit_roll = (EditText) findViewById(R.id.roll_show);
		edit_pitch = (EditText) findViewById(R.id.pitch_show);
		edit_yaw = (EditText) findViewById(R.id.yaw_show);
		edit_vx = (EditText) findViewById(R.id.vx_show);
		edit_vy = (EditText) findViewById(R.id.vy_show);
		edit_vz = (EditText) findViewById(R.id.vz_show);
		edit_dx = (EditText) findViewById(R.id.dx_show);
		edit_dy = (EditText) findViewById(R.id.dy_show);
		edit_dfi = (EditText) findViewById(R.id.dfi_show);
		edit_x = (EditText) findViewById(R.id.x_show);
		edit_y = (EditText) findViewById(R.id.y_show);
		edit_z = (EditText) findViewById(R.id.z_show);
		edit_rollgps = (EditText) findViewById(R.id.rollgps_show);
		edit_yawgps = (EditText) findViewById(R.id.yawgps_show);
		edit_pitchgps = (EditText) findViewById(R.id.pitchgps_show);
		edit_vxgps = (EditText) findViewById(R.id.vxgps_show);
		edit_vygps = (EditText) findViewById(R.id.vygps_show);
		edit_vzgps = (EditText) findViewById(R.id.vzgps_show);
		edit_xgps = (EditText) findViewById(R.id.xgps_show);
		edit_ygps = (EditText) findViewById(R.id.ygps_show);
		edit_zgps = (EditText) findViewById(R.id.zgps_show);
		edit_pdop = (EditText) findViewById(R.id.pdop_show);
		// Fly_status info above
		edit_p_x = (EditText) findViewById(R.id.p_x_show);
		edit_i_x = (EditText) findViewById(R.id.i_x_show);
		edit_d_x = (EditText) findViewById(R.id.d_x_show);
		edit_p_vx = (EditText) findViewById(R.id.p_vx_show);
		edit_i_vx = (EditText) findViewById(R.id.i_vx_show);
		edit_d_vx = (EditText) findViewById(R.id.d_vx_show);
		edit_p_pitch = (EditText) findViewById(R.id.p_pitch_show);
		edit_i_pitch = (EditText) findViewById(R.id.i_pitch_show);
		edit_d_pitch = (EditText) findViewById(R.id.d_pitch_show);
		edit_p_y = (EditText) findViewById(R.id.p_y_show);
		edit_i_y = (EditText) findViewById(R.id.i_y_show);
		edit_d_y = (EditText) findViewById(R.id.d_y_show);
		edit_p_vy = (EditText) findViewById(R.id.p_vy_show);
		edit_i_vy = (EditText) findViewById(R.id.i_vy_show);
		edit_d_vy = (EditText) findViewById(R.id.d_vy_show);
		edit_p_roll = (EditText) findViewById(R.id.p_roll_show);
		edit_i_roll = (EditText) findViewById(R.id.i_roll_show);
		edit_d_roll = (EditText) findViewById(R.id.d_roll_show);
		edit_p_yaw = (EditText) findViewById(R.id.p_yaw_show);
		edit_i_yaw = (EditText) findViewById(R.id.i_yaw_show);
		edit_d_yaw = (EditText) findViewById(R.id.d_yaw_show);
		edit_p_z = (EditText) findViewById(R.id.p_z_show);
		edit_i_z = (EditText) findViewById(R.id.i_z_show);
		edit_d_z = (EditText) findViewById(R.id.d_z_show);
		edit_p_vz = (EditText) findViewById(R.id.p_vz_show);
		edit_i_vz = (EditText) findViewById(R.id.i_vz_show);
		edit_d_vz = (EditText) findViewById(R.id.d_vz_show);*/
		edit_debug_time = (EditText) v.findViewById(R.id.debug_time_show);
		edit_debug_reserved = (EditText) v.findViewById(R.id.debug_reserved_show);
		edit_debug_infotype = (EditText) v.findViewById(R.id.debug_infotype_show);
		edit_debug_rcc = (EditText) v.findViewById(R.id.debug_rcc_show);
		edit_debug_rcr = (EditText) v.findViewById(R.id.debug_rcr_show);
		edit_debug_rcp = (EditText) v.findViewById(R.id.debug_rcp_show);
		edit_debug_rcy = (EditText) v.findViewById(R.id.debug_rcy_show);
		edit_debug_rct = (EditText) v.findViewById(R.id.debug_rct_show);
		edit_debug_pxset = (EditText) v.findViewById(R.id.debug_pxset_show);
		edit_debug_pyset = (EditText) v.findViewById(R.id.debug_pyset_show);
		edit_debug_pzset = (EditText) v.findViewById(R.id.debug_pzset_show);
		edit_debug_vxset = (EditText) v.findViewById(R.id.debug_vxset_show);
		edit_debug_vyset = (EditText) v.findViewById(R.id.debug_vyset_show);
		edit_debug_vzset = (EditText) v.findViewById(R.id.debug_vzset_show);
		edit_debug_axset = (EditText) v.findViewById(R.id.debug_axset_show);
		edit_debug_ayset = (EditText) v.findViewById(R.id.debug_ayset_show);
		edit_debug_azset = (EditText) v.findViewById(R.id.debug_azset_show);
		edit_debug_param1 = (EditText) v.findViewById(R.id.debug_param1_show);
		edit_debug_param2 = (EditText) v.findViewById(R.id.debug_param2_show);
		edit_debug_param3 = (EditText) v.findViewById(R.id.debug_param3_show);
		edit_debug_param4 = (EditText) v.findViewById(R.id.debug_param4_show);
		edit_debug_param5 = (EditText) v.findViewById(R.id.debug_param5_show);
		edit_debug_param6 = (EditText) v.findViewById(R.id.debug_param6_show);
		edit_debug_param7 = (EditText) v.findViewById(R.id.debug_param7_show);
		edit_debug_param8 = (EditText) v.findViewById(R.id.debug_param8_show);
		edit_debug_servo1 = (ProgressBar) v.findViewById(R.id.debug_servo1_show);
		edit_debug_servo2 = (ProgressBar) v.findViewById(R.id.debug_servo2_show);
		edit_debug_servo3 = (ProgressBar) v.findViewById(R.id.debug_servo3_show);
		edit_debug_servo4 = (ProgressBar) v.findViewById(R.id.debug_servo4_show);
		edit_debug_servo5 = (ProgressBar) v.findViewById(R.id.debug_servo5_show);
		edit_debug_servo6 = (ProgressBar) v.findViewById(R.id.debug_servo6_show);
		servo_value1 = (TextView) v.findViewById(R.id.servo_value_1);
		servo_value2 = (TextView) v.findViewById(R.id.servo_value_2);
		servo_value3 = (TextView) v.findViewById(R.id.servo_value_3);
		servo_value4 = (TextView) v.findViewById(R.id.servo_value_4);
		servo_value5 = (TextView) v.findViewById(R.id.servo_value_5);
		servo_value6 = (TextView) v.findViewById(R.id.servo_value_6);
		spinner = (Spinner) v.findViewById(R.id.spinner);

		//edit_systime = (EditText) findViewById(R.id.systime_show);// as the
																	// initial
																	// flag

		/*
		 * button_save = (Button) findViewById(R.id.save);
		 * button_save.setOnClickListener(new OnClickListener(){
		 * 
		 * @Override public void onClick(View arg0) { // TODO Auto-generated
		 * method stub Hashtable<String, Object> data = new Hashtable(); short
		 * type = 0xAA; int data1 = 0xFF; data.put("type", type);
		 * data.put("overrall", type); data.put("data1", data1);
		 * data.put("data2", data1); data.put("data3", data1); data.put("data4",
		 * data1); ControlNetwork.writeFram(1,
		 * ControlNetworkService.UPLOAD_CONTROL_COMMAND, data);
		 * //ControlNetwork.write("111".getBytes()); }
		 * 
		 * });
		 */
	}
	
	public static String getLocalIpAddress() {
		try {
			String ipv4;

			ArrayList<NetworkInterface> mylist = Collections
					.list(NetworkInterface.getNetworkInterfaces());

			for (NetworkInterface ni : mylist) {

				ArrayList<InetAddress> ialist = Collections.list(ni
						.getInetAddresses());
				for (InetAddress address : ialist) {
					if (!address.isLoopbackAddress()
							&& InetAddressUtils.isIPv4Address(ipv4 = address
									.getHostAddress())) {
						return ipv4;
					}
				}

			}

		} catch (SocketException ex) {

		}
		return null;
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
		// TODO Auto-generated method stub		
		//ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		
		
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		// TODO Auto-generated method stub
		
		
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		// TODO Auto-generated method stub
		mSurfaceView = null;
		
	}
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data){
		if (mMapsControlFragment == null){
			mMapsControlFragment = (MapsControlFragment) getSupportFragmentManager().findFragmentById(R.id.maps_control_fragment);				
		}
		switch(resultCode){
		case PopupActivity.RESULT_DELETE:
			//getFragmentManager().findFragmentById(R.id.maps_control_fragment).;
			//test.delete_fly_point_view(requestCode);			
			mMapsControlFragment.delete_fly_point_view(requestCode);			
			break;				
		case PopupActivity.RESULT_NONE:
			mMapsControlFragment.update_fly_point_high(requestCode, (Integer)data.getExtras().get("high"));
			break;
		case PopupActivity.RESULT_INSERT:
			mMapsControlFragment.insert_fly_point(requestCode);
			break;
		case PopupActivity.RESULT_UPLOAD:
			mMapsControlFragment.upload_fly_point(requestCode);
			break;
		case PopupActivity.RESULT_CANCEL:			
			break;
		}		
	}
	

	

}
